// pages/component/auth.js
const wh = require('../../utils/wh.js');
Component({
  /**
   * 组件的初始数据
   */
  data: {
    parent_id: 0,
    mobile_auth_modal: false // 授权窗口
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 授权判断
    onCheckMobile: function(mobile_validate) {
      let that = this;
      that.setData({
        mobile_auth_modal: false
      })
      if (mobile_validate != 1) {
        that.setData({
          mobile_auth_modal: true
        })
      }
      this.triggerEvent('myevent', {})
    },
    // 取消授权
    cancel_auth: function () {
      this.setData({
        mobile_auth_modal: false
      })
    },
    getPhoneNumber: function (e) {
      let that = this;
      if (e.detail.errMsg == 'getPhoneNumber:ok') {
        wx.showLoading({
          title: '申请中...',
        })

        that.update_session_key(e.detail.encryptedData, e.detail.iv, 1);
      }
    },
    /**
   * 更新session_key 
   */
    update_session_key: function (num_encrypted_data, num_iv, num_type) {
      let that = this;
      wx.login({
        success: function (res) {
          if (res.code) {
            wx.getSetting({
              success: function (auth) {
                if (auth.authSetting['scope.userInfo']) {
                  //#############授权后获取用户信息##############
                  wx.getUserInfo({
                    success: function (userInfo) {
                      let data = { code: res.code, encryptedData: userInfo.encryptedData, iv: userInfo.iv, rawData: userInfo.rawData, signature: userInfo.signature };
                      wh.Post('/api/user/login', data, function (info) {//登录成功返回的信息
                        that.setData({
                          mobile_auth_modal: false
                        })
                        // 用户同意电话收授权
                        let postUrl = '/api/user/decryptPhoneNumber',
                          postData = { encrypted_data: num_encrypted_data, iv: num_iv };
                        wh.Post(postUrl, postData, function() {});
                        wx.showToast({
                          title: '授权成功',
                        })
                        wx.setStorageSync('mobile_validate', 1)
                        setTimeout(function () {
                          wx.switchTab({
                            url: '/pages/index/index',
                            success: function (e) {
                              var page = getCurrentPages().pop();
                              if (page == undefined || page == null) return;
                              page.onShow();
                            }

                          })
                        }, 1500)
                      })
                    }
                  })
                }
              }
            })
          }
        }
      })
    }
  }
})
